package com.zjz.demo.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: zjz
 * @Date: 2021/10/10/9:57
 * @Description:
 * @Target:
 */
public class CASDemo1 {
        // CAS 比较并交换
    public static void main(String[] args) {


        // 对于我们平时写的SQL :乐观锁(version)!!

        // 两个参数,一个是要更新的,一个是版本号   注意第一个参数Integer,它取值要在-128~127,此时是在缓存中
        // 正常操作中都是对象
  AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(2, 1);






          new Thread(()->{

              int stamp = atomicStampedReference.getStamp();  // 获得目前的版本号

              System.out.println(Thread.currentThread().getName()+"1===>"+atomicStampedReference.getStamp());

              try {
                  TimeUnit.SECONDS.sleep(2);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }

              System.out.println(Thread.currentThread().getName()+"1===>"+atomicStampedReference.compareAndSet(2, 3,
                      atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));


              System.out.println(Thread.currentThread().getName()+"2===>"+atomicStampedReference.getStamp());

              System.out.println(Thread.currentThread().getName()+"2===>"+atomicStampedReference.compareAndSet(3, 2,
                      atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));


              System.out.println(Thread.currentThread().getName()+"3===>"+atomicStampedReference.getStamp());


          },"a").start();


        new Thread(()->{
            int stamp = atomicStampedReference.getStamp();  // 获得目前的版本号

                System.out.println(Thread.currentThread().getName()+"1===>"+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName()+"2===>"+atomicStampedReference.compareAndSet(2, 6,
                    stamp, stamp + 1));


            System.out.println(Thread.currentThread().getName()+"2===>"+atomicStampedReference.getStamp());

        },"b").start();




    }
}
